<template>
  <div>
    <!-- 消息图标和未读消息提示 -->
    <div class="message-icon" @click="showMessages">
      <span v-if="unreadCount > 0" class="badge">{{ unreadCount }}</span>
    </div>
    <!-- 消息列表展示 -->
    <div v-if="showMessageList" class="message-list">
      <div v-for="msg in messages" :key="msg.id">{{ msg.content }}</div>
    </div>
  </div>

</template>

<script>
export default {
  data() {
    return {
      socket: null,
      messages: [],
      unreadCount: 0,   // 未读消息计数
      showMessageList: false // 是否显示消息列表
    };
  },
  mounted() {
    this.connect(); // 组件挂载后，建立 WebSocket 连接
  },
  methods: {
    connect() {
      // // 获取 JWT token
      // const token = localStorage.getItem('token');
      //
      // // 解析 JWT token 获取 userId
      // function getUserIdFromToken(token) {
      //   if (!token) return null;
      //   const payload = token.split('.')[1]; // 获取中间部分
      //   const decodedPayload = JSON.parse(atob(payload)); // 解码为对象
      //   return decodedPayload.userId; // 获取 userId
      // }
      //
      // const userId = getUserIdFromToken(token);
      //
      // console.log('Token:', token);
      // console.log('User ID:', userId);
      // 使用原生 WebSocket 连接
      this.socket = new WebSocket("ws://localhost:8080/websocket-endpoint?userId=1");
      this.socket.onopen = () => {
        console.log("WebSocket connected");
      };
      this.socket.onmessage = (event) => {
        const receivedMessage = JSON.parse(event.data);
        console.log("Received message:", receivedMessage);
        this.messages.push(receivedMessage);
        this.unreadCount++;  // 增加未读消息计数
      };
      this.socket.onclose = () => {
        console.log("WebSocket disconnected");
      };
      this.socket.onerror = (error) => {
        console.error("WebSocket error:", error);
      };
    },
    showMessages() {
      this.showMessageList = true;
      this.unreadCount = 0;
    }
  }
};
</script>

<style scoped>
.message-icon {
  position: relative;
  cursor: pointer;
}

.badge {
  display: inline-block;
  min-width: 20px;
  padding: 3px 7px;
  font-size: 12px;
  font-weight: bold;
  color: white;
  background-color: red;
  border-radius: 10px;
  position: absolute;
  top: 5px;
  right: 5px;
}

.message-list {
  position: absolute;
  top: 30px;
  right: 0;
  width: 200px;
  background: white;
  border: 1px solid #ccc;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
}
</style>
